#!/bin/bash

VER=`cat ../core/package.json | grep version`
VER=${VER#*:*\"}
VER=${VER%\.*}

OLDVER=`cat ./ver`

if [[ $VER == $OLDVER ]]
then
    echo "====skip===============$VER"
    exit
fi

echo "===================line : $OLDVER => $VER"

#########################################################

#OLDPORT=`cat ./port`

#if [[ $OLDPORT == 5100 ]]
#then
#    OLDPORT=5000
#else
#    OLDPORT=$[ $OLDPORT + 1 ]
#fi

#echo $OLDPORT > ./port
OLDPORT=5000

#########################################################

cat > ./start_service.sh <<EOF
#!/bin/sh
serve -l ${OLDPORT} -s -c /app/serve.json /app/ & envoy -c /etc/service-envoy.yaml --service-cluster service_line
EOF

#########################################################

ETAG=${VER//\./dot}

echo $VER > ./ver

rm -rf ./build
cp -r ../core/build .

cat > ./serve.json <<EOF
{
    "headers": [
        {
            "source": "**",
            "headers": [{
                    "key": "ETag",
                    "value": "$ETAG"
                },{
                    "key": "Cache-Control",
                    "value": "no-cache"
                }]
        }
    ]
}
EOF

#########################################################

cat > ./service-envoy.yaml <<EOF
static_resources:
  listeners:
  - address:
      socket_address:
        address: 0.0.0.0
        port_value: 80
    filter_chains:
    - filters:
      - name: envoy.http_connection_manager
        config:
          codec_type: auto
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: service
              domains:
              - "*"
              routes:
              - match:
                  prefix: "/"
                route:
                  cluster: service_line
          http_filters:
          - name: envoy.router
            config: {}
  clusters:
  - name: service_line
    connect_timeout: 100s
    type: strict_dns
    lb_policy: round_robin
    hosts:
    - socket_address:
        address: 127.0.0.1
        port_value: ${OLDPORT}
admin:
  access_log_path: "/dev/null"
  address:
    socket_address:
      address: 0.0.0.0
      port_value: 8081
EOF

#########################################################

docker build -t line:$VER .
